from pydantic import BaseModel, Field, validator
from typing import List, Optional
from datetime import datetime

class ProductSpecs(BaseModel):
    """商品规格属性"""
    target_species: List[str] = Field(..., min_items=1, 
                                    description="适用物种，使用['Dog','Cat','Bird']标准形式")
    target_breeds: Optional[List[str]] = Field(None, 
                                             description="适用品种FCI编码列表")
    weight: Optional[float] = Field(None, ge=0, 
                                  description="单位：克/毫升，需统一转换")
    size: Optional[str] = Field(None, regex=r"^[A-Z]（.*\d+.*）$",
                              example="S（胸围30cm）")

class IngredientsMaterials(BaseModel):
    """成分/材料结构化模型"""
    ingredients: Optional[List[str]] = Field(None, 
                                           description="标准成分名称，食品类必填")
    material: Optional[List[str]] = Field(None,
                                        description="标准材料名称，用品类必填")

    @validator('*', pre=True, each_item=True)
    def check_standard_terms(cls, v):
        # 这里需接入成分/材料标准库校验（示例逻辑）
        standard_terms = get_standard_terms()  # 假设从数据库获取标准术语
        if v not in standard_terms:
            raise ValueError(f"非标准术语: {v}")
        return v

class AlignedPetProduct(BaseModel):
    """对齐后的宠物商品数据模型"""
    # 核心标识
    product_id: str = Field(..., min_length=10, 
                          description="全球唯一商品ID，格式如PET-XXXX-XX")

    # 基础信息
    product_name: str = Field(..., max_length=100,
                            description="清洗后的商品名称（去促销词、统一大小写）")
    brand: str = Field(..., description="品牌标准英文名")

    # 分类体系
    category: str = Field(..., regex="^(食品|用品|药品)$")
    sub_category: str = Field(...,
                             regex="^(主粮|零食|玩具|窝垫|驱虫药|营养膏)$")

    # 规格与成分
    specs: ProductSpecs
    composition: Optional[IngredientsMaterials] = Field(None)

    # 多模态特征
    text_embedding: List[float] = Field(..., min_items=768, max_items=768)
    image_embedding: Optional[List[float]] = Field(None, min_items=1024, max_items=1024)
    image_hash: Optional[str] = Field(None, min_length=16, 
                                    description="感知哈希值（16位hex）")

    # 供应链信息
    supplier_code: str = Field(..., regex=r"^GS1\d{10}$")
    batch_number: Optional[str] = Field(None, regex=r"^\d{4}[A-Z]\d{2}$")

    # 价格库存
    price: float = Field(..., gt=0, description="人民币标准价格")
    stock_status: int = Field(..., ge=0, le=2)

    # 对齐元数据
    source_db: str = Field(..., description="来源数据库标识")
    alignment_score: float = Field(..., ge=0, le=1)
    last_aligned_time: datetime = Field(default_factory=datetime.now)

    # 自定义校验示例：药品必须包含批次号
    @validator('batch_number')
    def validate_batch_number(cls, v, values):
        if values.get('category') == '药品' and not v:
            raise ValueError("药品类必须提供批次号")
        return v

def get_standard_terms() -> List[str]:
    """获取标准术语列表（示例实现）"""
    # TODO: 实现从数据库获取标准术语的逻辑
    return ["鸡肉", "牛肉", "鱼肉", "棉", "聚酯纤维"]
